package com.grouppurchase.controller;

import com.grouppurchase.common.Result;
import com.grouppurchase.entity.TraditionalGroup;
import com.grouppurchase.service.GroupService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/group")
@Api(tags = "团购管理", description = "提供团购相关的管理接口")
public class GroupController {

    @Autowired
    private GroupService groupService;
    
    @GetMapping("/product/{productId}")
    @ApiOperation(value = "获取商品团购列表", notes = "根据商品ID获取当前进行中的团购列表")
    public Result<List<TraditionalGroup>> getGroupsByProduct(@ApiParam(value = "商品ID", required = true) @PathVariable Long productId) {
        List<TraditionalGroup> groups = groupService.getActiveGroupsByProduct(productId);
        return Result.success(groups);
    }

    @PostMapping("/create")
    @ApiOperation(value = "创建团购", notes = "为指定商品创建新的团购活动")
    public Result<TraditionalGroup> createGroup(@ApiParam(value = "商品ID", required = true) @RequestParam Long productId,
                                               @ApiParam(value = "成团目标人数", required = true) @RequestParam Integer targetSize) {
        TraditionalGroup group = groupService.createGroup(productId, targetSize);
        return Result.success(group);
    }

    @PostMapping("/join")
    @ApiOperation(value = "加入团购", notes = "用户加入指定的团购活动")
    public Result<Boolean> joinGroup(@ApiParam(value = "团购ID", required = true) @RequestParam Long groupId,
                                    @ApiParam(value = "用户ID", required = true) @RequestParam Long userId) {
        boolean success = groupService.joinGroup(groupId, userId);
        return success ? Result.success() : Result.error("加入团购失败");
    }

    @GetMapping("/detail/{groupNo}")
    @ApiOperation(value = "获取团购详情", notes = "根据团购编号获取团购详细信息")
    public Result<TraditionalGroup> getGroupDetail(@ApiParam(value = "团购编号", required = true) @PathVariable String groupNo) {
        TraditionalGroup group = groupService.getGroupByNo(groupNo);
        if (group != null) {
            return Result.success(group);
        }
        return Result.error("团购不存在");
    }
}
